package org.xx.bookstore.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.xx.armory.spring5.mvc.BusinessLogicException;

import static org.xx.armory.spring5.mvc.ModelUtils.buildJsonView;
import static org.xx.armory.spring5.mvc.ModelUtils.paramGreaterThan;

@Controller
@RequestMapping("/demo")
public class DemoController {
    @PostMapping("/error")
    public ModelAndView error(
            @RequestParam("d1") int d1
    ) {
        paramGreaterThan(d1, 0, "Must be positive");

        if (d1 == 3) {
            throw new RuntimeException("Illegal d1");
        } else if (d1 == 4) {
            throw new BusinessLogicException(4).addExtra("key1", "abc").addExtra("key2", 2000);
        }

        return buildJsonView(d1);
    }

    @PostMapping("/error2")
    public ModelAndView error2() {
        return buildJsonView("pass");
    }

    @PostMapping("/error3")
    public ModelAndView error3() {
        return buildJsonView(null);
    }
}
